package com.bangdao.juc;

/**
 * @author chen
 * @create 2021-01-02
 */

/**
 * 30个人抢票
 */
public class SalTicket {
    public static void main(String[] args) {
        //创建同一个资源 模拟并发 不能在线程内部创建
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}

/**
 * 20张票
 * 资源类
 */
class Ticket {
    private Integer number = 20;

    //封装卖票方法 synchronized加锁防止超卖
    public synchronized void sale() {
        if (number <= 0) {
            System.out.println("票已售完！");
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        number--;
        System.out.println("买票成功,当前剩余：" + number + "张");
    }
}
